package com.dream.cgomall.service.impl;

import com.dream.cgomall.dao.CgoActiveRedpackageDao;
import com.dream.cgomall.dao.CgoAdminWalletDao;
import com.dream.cgomall.dto.RedPackage;
import com.dream.cgomall.entity.CgoActiveRedpackage;
import com.dream.cgomall.service.CgoRedPackageSevice;
import com.dream.cgomall.service.ServiceResult;
import com.dream.cgomallcore.util.GenerateRedPackageQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@Service
public class CgoRedPackageSeviceImpl implements CgoRedPackageSevice {
    public final static Map<Integer, RedPackage> map = new ConcurrentHashMap();
    @Autowired(required = false)
    CgoActiveRedpackageDao cgoActiveRedpackageDao;
    @Autowired(required = false)
    CgoAdminWalletDao cgoAdminWalletDao;



    @Override
    public ServiceResult addRedPackageAtive(CgoActiveRedpackage cgoActiveRedpackage) {
        try {
            if(cgoActiveRedpackageDao.insertactive(cgoActiveRedpackage)<=0){
                return ServiceResult.badResult("当前活动还未结束");
            }
            Double money = Double.parseDouble(cgoActiveRedpackage.getPrice().toString());
            int count = cgoActiveRedpackage.getMany();
            Queue<Double> queue = GenerateRedPackageQueue.createQueue(count, money);
            RedPackage redPackage = new RedPackage(cgoActiveRedpackage.getMany(), queue,new HashSet<>(count));
            map.put(cgoActiveRedpackage.getUserId(), redPackage);
        } catch (RuntimeException e) {
            System.out.println(e);
            return ServiceResult.badResult("添加失败");
        }
        return ServiceResult.success();
    }
    @Transactional
    @Override
    public ServiceResult collectionRedPackage(Integer userId,Integer getPackageUserId) {
        try {
            if (map.containsKey(userId)) {
                if(!map.get(userId).getHasGetSet().contains(getPackageUserId)) {
                    if (map.get(userId).getMany().decrementAndGet() >= 0) {
                        double pollMoney = map.get(userId).getRedPackageQueue().poll();
                        map.get(userId).getHasGetSet().add(getPackageUserId);
                        cgoAdminWalletDao.updateUserMoney(pollMoney, getPackageUserId);
                        return ServiceResult.of(pollMoney);
                    } else {
                        cgoActiveRedpackageDao.updateActiveOver(userId);
                        map.put(userId, null);
                        return ServiceResult.badResult("您手慢了，没抢到呢亲");
                    }
                }else {
                    return ServiceResult.badResult("您已经抢过了");
                }
            }
        }catch (RuntimeException e){
            return ServiceResult.badResult("您手慢了，没抢到呢亲");
        }
        return ServiceResult.badResult("活动已结束");
    }

    @Transactional
    @Override
    public ServiceResult getRedPackageInfo(Integer userId) {
        if (map.get(userId) != null) {
            CgoActiveRedpackage cgoActiveRedpackage = cgoActiveRedpackageDao.selectByUserId(userId);
            if (cgoActiveRedpackage == null) {
                return ServiceResult.of(null);
            } else if (cgoActiveRedpackage.getEndTime().isBefore(LocalDateTime.now())) {
                cgoActiveRedpackageDao.updateActiveOver(userId);
                map.put(userId, null);
                return ServiceResult.badResult("您来晚了，活动已结束");
            } else {
                return ServiceResult.of(cgoActiveRedpackage);
            }
        }
        return ServiceResult.badResult("活动已结束");
    }

    @Override
    public ServiceResult refreshActive() {
        List<CgoActiveRedpackage> cgoActiveRedpackageList = cgoActiveRedpackageDao.selectAll();
        cgoActiveRedpackageList.forEach((elem)->{
            if(elem.getEndTime().isBefore(LocalDateTime.now())){
                map.remove(elem.getUserId());
                cgoActiveRedpackageDao.updateActiveOver(elem.getUserId());
            }else if(map.get(elem.getUserId())==null){
                Double money = Double.parseDouble(elem.getPrice().toString());
                int count = elem.getMany();
                Queue<Double> queue = GenerateRedPackageQueue.createQueue(count, money);
                RedPackage redPackage = new RedPackage(elem.getMany(), queue,new HashSet<>(count));
                map.put(elem.getUserId(), redPackage);
            }
        });
        return ServiceResult.success();
    }
}
